import React, { ChangeEventHandler, useEffect } from 'react';
import { useState } from 'react';
import classNames from 'classnames';
import { useConfigProvider } from '../mat-config-provider';
import './style/index.less';

export interface SwitchProps {
  /**
   * 开关状态
   */
  value?: any;
  /**
   * 是否禁用
   */
  disabled?: boolean;
  /**
   * 开关打开时的对应值
   */
  activeValue?: any;
  /**
   * 开关关闭时的对应值
   */
  inActiveValue?: any;
  /**
   * 额外附加内容
   */
  extra?: React.ReactNode;
  /**
   * 变化回调
   */
  onChange?: (value: boolean) => void;
}

const MatSwitch: React.FC<SwitchProps> = ({
  value = false,
  disabled = false,
  activeValue = true,
  inActiveValue = false,
  extra = null,
  onChange,
}) => {
  const { prefixCls } = useConfigProvider();
  const isChecked = (value: any) => (value === activeValue ? true : false);
  const [checked, setChecked] = useState(isChecked(value));

  const onInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    if (!disabled) {
      const newValue = isChecked(checked) === activeValue ? inActiveValue : activeValue;
      setChecked(e.target.checked);
      onChange?.(newValue);
    }
  };

  return (
    <div className={`${prefixCls}-switch-wrapper`}>
      {extra}
      <div className={`${prefixCls}-switch`}>
        <input
          disabled={disabled}
          type="checkbox"
          checked={checked}
          onChange={onInputChange}
          className={`${prefixCls}-switch-checkbox`}
        />
        <div
          className={classNames(`${prefixCls}-switch-core`, {
            'is-checked': checked,
          })}
        />
      </div>
    </div>
  );
};

export default MatSwitch;
